<template>
  <div class="flex flex-col h-full p-4">
    <!-- 详情页面 -->
    <EarlyWarningDetail v-if="showDetailsRef" :warning-id="detailId" @go-back="goBackToList" />

    <!-- Early Warning Container with white background -->
    <div v-else class="flex-1 flex flex-col bg-white rounded-lg shadow p-6 min-h-0">
      <!-- 页面标题 -->
      <h1 class="text-2xl font-bold pb-6">Early Warning</h1>

      <!-- Filter section -->
      <div class="mb-6">
        <!-- 上栏筛选条件 -->
        <div class="flex items-center gap-4 mb-4">
          <!-- 电池包SN/设备SN搜索 -->
          <el-input v-model="filters.batteryPackSN" placeholder="Battery Pack SN/Device SN" clearable class="w-70!">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>

          <!-- 状态选择 -->
          <el-select v-model="filters.status" placeholder="All status" clearable class="w-44!">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <!-- 电池类型选择 -->
          <el-select v-model="filters.batteryType" placeholder="All battery type" clearable class="w-44!">
            <el-option v-for="item in batteryTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <!-- 告警名称选择 -->
          <el-select v-model="filters.alertName" placeholder="All alert name" clearable class="w-44!">
            <el-option v-for="item in alertNameOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <!-- 下栏筛选条件 -->
        <div class="flex items-center gap-4">
          <!-- 发生时间范围 -->
          <div class="flex items-center">
            <span class="mr-2">Occurrence time:</span>
            <el-date-picker v-model="occurrenceTimeRange" type="daterange" range-separator="→"
              start-placeholder="2020-11-08" end-placeholder="2020-12-23" class="w-64!" />
          </div>

          <!-- 检测时间范围 -->
          <div class="flex items-center">
            <span class="mr-2">Detect time:</span>
            <el-date-picker v-model="detectTimeRange" type="daterange" range-separator="→"
              start-placeholder="Start date" end-placeholder="End date" class="w-64!" />
          </div>

          <!-- 操作按钮 -->
          <div class="flex ml-auto">
            <el-button @click="resetFilters">Reset</el-button>
            <el-button type="primary" @click="searchWarnings">Search</el-button>
          </div>
        </div>
      </div>

      <!-- 表格部分 -->
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="displayedWarnings.length > 0"
        @retry="retryFetch"
      >
        <EarlyWarningTable
          :warning-data="displayedWarnings"
          :pagination="pagination"
          @page-change="handleCurrentChange"
          @size-change="handleSizeChange"
          @detail="showDetails"
          class="flex-1"
        />
      </PageState>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onUnmounted, onDeactivated, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { type EarlyWarningItem, statusOptions, batteryTypeOptions as staticBatteryTypeOptions, alertNameOptions as staticAlertNameOptions } from "./data";
import EarlyWarningTable from "./components/EarlyWarningTable.vue";
import EarlyWarningDetail from "./components/EarlyWarningDetail.vue";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";
import { bmsApi } from "@/api/bms";
import { ElMessage } from "element-plus";

// 切换到详情页面
const showDetailsRef = ref(false);

// 详情页面id
const detailId = ref("");

// 筛选条件
const filters = reactive({
  batteryPackSN: "",
  status: "",
  batteryType: "",
  alertName: ""
});

// 时间范围
const occurrenceTimeRange = ref([]);
const detectTimeRange = ref([]);

// 下拉选项（初始为静态，后续从接口数据补齐）
const statusOptionsRef = ref([...statusOptions]);
const batteryTypeOptions = ref([...staticBatteryTypeOptions]);
const alertNameOptions = ref([...staticAlertNameOptions]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 列表数据
const earlyWarnings = ref<EarlyWarningItem[]>([]);
const displayedWarnings = computed(() => earlyWarnings.value);

// 获取列表
const fetchWarningList = async () => {
  loading.value = true;
  errorMessage.value = "";
  try {
    const params: any = {
      page: pagination.currentPage.toString(),
      limit: pagination.pageSize.toString()
    };
    if (filters.batteryPackSN) {
      params.batteryPackSn = filters.batteryPackSN;
      params.deviceSn = filters.batteryPackSN;
    }
    if (filters.status) params.status = filters.status.toLowerCase();
    if (filters.batteryType) params.batteryType = filters.batteryType;
    if (filters.alertName) params.alertName = filters.alertName;
    if (occurrenceTimeRange.value?.length === 2) {
      params.predictedTime = `${formatDateTime(occurrenceTimeRange.value[0])}-${formatDateTime(occurrenceTimeRange.value[1])}`;
    }
    if (detectTimeRange.value?.length === 2) {
      params.detectTime = `${formatDateTime(detectTimeRange.value[0])}-${formatDateTime(detectTimeRange.value[1])}`;
    }

    const res = await bmsApi.getEarlyWarningPage(params);
    if (res.code === 0) {
      const list = (res.data?.list || []).map((it: any) => ({
        id: String(it.id ?? ""),
        batteryPackSN: it.batteryPackSn ?? "",
        deviceSN: it.deviceSn ?? "",
        alertName: it.alertName ?? "",
        batteryType: it.batteryType ?? "",
        capacity: Number(it.capacity ?? 0),
        predictedTime: it.predictedTime ?? "",
        detectTime: it.detectTime ?? "",
        status: (typeof it.status === 'number' ? (it.status === 0 ? 'Open' : 'Close') : (String(it.status).toLowerCase() === 'open' ? 'Open' : 'Close')) as 'Open' | 'Close'
      })) as EarlyWarningItem[];
      earlyWarnings.value = list;
      pagination.total = res.data?.total || 0;

      // 从列表补充下拉选项（不改变现有样式，仅数据来源）
      const types = Array.from(new Set(list.map(i => i.batteryType).filter(Boolean)));
      batteryTypeOptions.value = [
        { value: "", label: "All battery type" },
        ...types.map(t => ({ value: t, label: t }))
      ];
      const names = Array.from(new Set(list.map(i => i.alertName).filter(Boolean)));
      alertNameOptions.value = [
        { value: "", label: "All alert name" },
        ...names.map(n => ({ value: n, label: n }))
      ];
    } else {
      throw new Error(res.msg || '获取预警列表失败');
    }
  } catch (e: any) {
    errorMessage.value = e.message || '网络错误';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

function formatDateTime(d: any) {
  try {
    return d.toISOString().slice(0, 19);
  } catch {
    return '';
  }
}

// 方法
const resetFilters = () => {
  filters.batteryPackSN = "";
  filters.status = "";
  filters.batteryType = "";
  filters.alertName = "";
  occurrenceTimeRange.value = [];
  detectTimeRange.value = [];
  pagination.currentPage = 1;
  fetchWarningList();
};

const searchWarnings = () => {
  // 重置分页到第一页
  pagination.currentPage = 1;
  fetchWarningList();
};

// 防抖输入
const debouncedSearch = useDebounce(() => {
  searchWarnings();
}, 500, { leading: false, trailing: true });

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  // 切换每页显示数量时重置到第一页
  pagination.currentPage = 1;
  fetchWarningList();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchWarningList();
};

const showDetails = (row: EarlyWarningItem) => {
  // 跳转到详情页面
  showDetailsRef.value = true;
  detailId.value = row.id;
};

const goBackToList = () => {
  showDetailsRef.value = false;
  detailId.value = "";
};

onDeactivated(() => {
  showDetailsRef.value = false;
  detailId.value = "";
});

onUnmounted(() => {
  showDetailsRef.value = false;
  detailId.value = "";
});

// 状态与重试（预留真实接口时使用）
const loading = ref(false);
const errorMessage = ref("");
const retryFetch = () => {
  errorMessage.value = "";
  fetchWarningList();
};

onMounted(() => {
  fetchWarningList();
});
</script>

<style lang="scss" scoped>
:deep(.warning-details-dialog) {
  max-height: 80vh;

  .el-dialog__body {
    max-height: calc(80vh - 120px);
    overflow-y: auto;
    padding: 20px;
  }
}
</style>
